<template>
    <div class="madp-wechat-task">
        <basic-container v-show="!showDetail">
            <div class="madp-search-head">
                <el-form class="madp-form" inline>
                    <el-form-item label="创建者:">
                        <el-input v-model.trim="searchForm.createUserName" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="任务标题:">
                        <el-input v-model.trim="searchForm.title" maxlength="30"></el-input>
                    </el-form-item>
                    <el-form-item label="开始时间:">
                        <el-date-picker
                            v-model="searchForm.time"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            range-separator="至   "
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="madp-search-form">
                <el-button class="madp-btn" v-if="permissions.cp_wechat_moments_add" type="primary" @click="handleAdd">新建</el-button>
            </div>
            <unitTitle title="任务详情" />
            <table-node ref="table1" :searchForm="searchForm" @handleView="handleView" @handleEdit="handleEdit" :tableType="1" />
            <table-node ref="table2" :searchForm="searchForm" @handleView="handleView" @handleEdit="handleEdit" @handleUpdate="getList(1)" />
        </basic-container>
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :before-close="dialogCustomerClose" :close-on-click-modal="false">
            <el-form v-if="dialogVisible" class="madp-form-style" ref="form" :rules="rule" :model="form" label-width="140px" v-loading="dialogLoading" :disabled="dialogTitle == '查看任务'">
                <el-form-item label="朋友圈类型:" prop="filterType">
                    <el-select v-model="form.filterType">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标题:" prop="title">
                    <el-input v-model.trim="form.title" placeholder="朋友圈任务标题仅后台可见" maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="朋友圈内容:" prop="content">
                    <el-input type="textarea" show-word-limit v-model.trim="form.content" placeholder="请输入朋友圈内容" maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="开始时间:" prop="beginTime">
                    <el-date-picker v-model="form.beginTime" type="date" value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间:" prop="endTime">
                    <el-date-picker :disabled="!form.beginTime" v-model="form.endTime" type="date" value-format="yyyy-MM-dd" :picker-options="pickerOptions2"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <video v-if="uploadType == 2" :src="form.imgUrl[0]" controls="controls" class="video" />
                    <el-upload
                        action="#"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-change="onChange"
                        :auto-upload="false"
                        :file-list="fileList"
                        :multiple="false"
                        v-loading="uploadLoading"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="imgViewDialogVisible" :close-on-click-modal="false">
                        <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="选择成员:" prop="people">
                    <el-button type="primary" @click="chooseMember">选择成员</el-button>
                </el-form-item>
                <el-form-item v-if="form.people.length > 0">
                    <el-tag class="tag" v-for="item in form.people" :key="item.id + item.name" :disable-transitions="false">{{ item.name }}</el-tag>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button v-show="dialogTitle != '查看任务'" type="primary" @click="surinFn">提交</el-button>
                <el-button :type="dialogTitle == '查看任务' ? 'primary' : ''" @click="dialogCustomerClose">{{ dialogTitle == '查看任务' ? '确定' : '取消' }}</el-button>
            </span>
        </el-dialog>
        <add-staff
            v-if="showAddStaff"
            ref="addStaff"
            :showAddStaff="showAddStaff"
            :receivingEmployees="dataSubscription"
            @addStaffCloseFn="addStaffCloseFn"
            @addStaffconfirmFn="addStaffconfirmFn"
        ></add-staff>
        <basic-container v-show="showDetail">
            <BackTitle title="任务详情" @goBack="goBack" />
        </basic-container>
        <TaskDetail :id="taskId" v-if="showDetail" />
    </div>
</template>
<script>
import addStaff from '@/components/wechat/add-staff';
import TaskDetail from './wechat-details.vue';
import tableNode from './table.vue';
import { sysFileUpload } from '@/api/customer-into/marketing-material';
import { addTask, getTaskDetail, editTask, pubTask } from '@/api/customer/wechat-task';
import { mapGetters } from 'vuex';
const validatePeople = (rule, value, callback) => {
    if (value.length === 0) {
        callback(new Error('请选择成员'));
    } else {
        callback();
    }
};
export default {
    name: 'madp-wechat-task',
    components: {
        addStaff,
        TaskDetail,
        tableNode
    },
    data() {
        const validateEndTime = (rule, value, callback) => {
            if (new Date(this.form.beginTime) > new Date(this.form.endTime)) {
                callback(new Error('结束时间不能在开始时间之前'));
            } else {
                callback();
            }
        };
        return {
            showDetail: false,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
                }
            },
            pickerOptions2: {
                disabledDate: (time) => {
                    if (!this.form.beginTime) {
                        return false;
                    }
                    return (
                        time.getTime() < new Date(this.form.beginTime.replace(/-/g, '/')).getTime() ||
                        time.getTime() > new Date(this.form.beginTime.replace(/-/g, '/')).getTime() + 2 * 24 * 60 * 60 * 1000
                    );
                }
            },
            form: {
                beginTime: '',
                endTime: '',
                content: '',
                deptId: [],
                employeeId: [],
                filterType: 0,
                imgUrl: [],
                title: '',
                people: []
            },
            rule: {
                filterType: [
                    {
                        required: true
                    }
                ],
                title: [
                    {
                        required: true,
                        message: '请输入朋友圈任务标题',
                        trigger: 'blur'
                    }
                ],
                content: [
                    {
                        required: true,
                        message: '请输入朋友圈任务内容',
                        trigger: 'blur'
                    }
                ],
                beginTime: [
                    {
                        required: true,
                        message: '请选择开始时间',
                        trigger: 'change'
                    }
                ],
                endTime: [
                    {
                        required: true,
                        message: '请选择结束时间',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        validator: validateEndTime
                    }
                ],
                people: [
                    {
                        required: true,
                        validator: validatePeople
                    }
                ]
            },
            dialogVisible: false,
            dialogTitle: '',
            dialogLoading: false,
            options: [
                {
                    label: '企业微信朋友圈',
                    value: 0
                },
                {
                    label: '个人微信朋友圈',
                    value: 1
                }
            ],
            dialogImageUrl: '',
            imgViewDialogVisible: false,
            uploadLoading: false,
            showAddStaff: false,
            dataSubscription: {},
            fileList: [],
            searchForm: {
                createUserName: '',
                title: '',
                time: []
            },
            taskId: '',
            uploadType: null // 1 图片  2 视频
        };
    },
    watch: {
        'form.employeeId': {
            handler(val) {
                this.form.people = [...this.form.deptId, ...this.form.employeeId];
                if (this.$refs.form) {
                    this.$refs.form.validateField('people');
                }
            }
        },
        'form.deptId': {
            handler(val) {
                this.form.people = [...this.form.deptId, ...this.form.employeeId];
                if (this.$refs.form) {
                    this.$refs.form.validateField('people');
                }
            }
        }
    },
    computed: {
        ...mapGetters(['permissions'])
    },
    methods: {
        getList(data) {
            this.$refs.table1.getList(data);
            this.$refs.table2.getList(data);
        },
        chooseMember() {
            this.dataSubscription = {
                userIds: JSON.parse(JSON.stringify(this.form.employeeId)),
                deptIds: JSON.parse(JSON.stringify(this.form.deptId))
            };
            this.showAddStaff = true;
        },
        addStaffconfirmFn(data) {
            this.form.employeeId = data.userIds;
            this.form.deptId = data.deptIds;
            this.showAddStaff = false;
        },
        addStaffCloseFn() {
            this.showAddStaff = false;
        },
        handleAdd() {
            this.uploadType = null;
            this.dialogTitle = '新建任务';
            this.fileList = [];
            this.dialogVisible = true;
            this.form = {
                time: [],
                content: '',
                deptId: [],
                employeeId: [],
                filterType: 0,
                imgUrl: [],
                title: '',
                people: []
            };
        },
        handleSearch() {
            this.getList();
        },
        handleReset() {
            this.searchForm = {
                createUserName: '',
                title: '',
                time: []
            };
            this.getList();
        },
        handleView(data) {
            this.taskId = data.id;
            this.showDetail = true;
        },
        handleEdit(data) {
            getTaskDetail(data.id).then((res) => {
                let { beginTime, endTime, id, content, title, imgUrl, filterType, deptS, employeeLists } = res.data.data,
                    deptId = (deptS || []).map((i) => {
                        return {
                            name: i.deptIdName,
                            id: i.deptIds
                        };
                    }),
                    employeeId = (employeeLists || []).map((i) => {
                        return {
                            name: i.employeeName,
                            id: i.employeeId
                        };
                    });
                this.form = {
                    id,
                    beginTime,
                    endTime,
                    content,
                    title,
                    imgUrl,
                    deptId,
                    employeeId,
                    filterType,
                    people: []
                };
                this.fileList = imgUrl.map((i) => {
                    return {
                        url: i
                    };
                });
                if (data.val) {
                    this.dialogTitle = '查看任务';
                } else {
                    this.dialogTitle = '编辑任务';
                }
                if (imgUrl.length == 1 && ['.mp4', '.ogg', '.flv', '.avi', '.wmv', '.rmvb', '.mov'].includes(imgUrl[0].slice(imgUrl[0].indexOf('.')))) {
                    this.uploadType = 2;
                    this.fileList = [];
                } else {
                    this.uploadType = 1;
                }
                this.dialogVisible = true;
            });
        },
        dialogCustomerClose() {
            this.dialogVisible = false;
        },
        surinFn() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let { id, imgUrl, title, content, filterType, beginTime, endTime, deptId, employeeId } = this.form,
                        arr1 = deptId.map((i) => {
                            return i.id;
                        }),
                        arr2 = employeeId.map((i) => {
                            return i.id;
                        }),
                        form = {
                            beginTime,
                            endTime,
                            deptId: arr1,
                            employeeId: arr2,
                            filterType,
                            title,
                            content,
                            imgUrl
                        };
                    if (deptId.length + employeeId.length === 0) {
                        return;
                    }
                    this.dialogLoading = true;
                    if (this.dialogTitle == '新建任务') {
                        addTask(form)
                            .then((res) => {
                                if (res.data.code != 0) return;
                                this.$message({
                                    type: 'success',
                                    message: '新增成功!'
                                });
                                this.getList(1);
                                this.dialogLoading = false;
                                this.dialogVisible = false;
                            })
                            .catch(() => {
                                this.dialogLoading = false;
                            });
                    } else {
                        form.id = id;
                        editTask(form)
                            .then((res) => {
                                if (res.data.code != 0) return;
                                this.$message({
                                    type: 'success',
                                    message: '编辑成功!'
                                });
                                this.getList(1);
                                this.dialogLoading = false;
                                this.dialogVisible = false;
                            })
                            .catch(() => {
                                this.dialogLoading = false;
                            });
                    }
                }
            });
        },
        handleRemove(file, fileList) {
            this.fileList = fileList;
            let arr = fileList.map((i) => {
                return i.url;
            });
            this.form.imgUrl = arr;
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.imgViewDialogVisible = true;
        },
        onChange(file, fileList) {
            let type = file.raw.type;
            if (fileList.length == 1) {
                if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].includes(type)) {
                    this.uploadType = 2;
                } else if (['image/png', 'image/jpg', 'image/jpeg'].includes(type)) {
                    this.uploadType = 1;
                } else {
                    this.$message.error('请上传video/mp4, video/ogg, video/flv, video/avi, video/wmv, video/rmvb, video/mov,image/png, image/jpg, image/jpeg格式文件');
                    return false;
                }
            } else {
                let curType = null;
                if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].includes(type)) {
                    curType = 2;
                } else if (['image/png', 'image/jpg', 'image/jpeg'].includes(type)) {
                    curType = 1;
                } else {
                    this.$message.error('请上传video/mp4, video/ogg, video/flv, video/avi, video/wmv, video/rmvb, video/mov,image/png, image/jpg, image/jpeg格式文件');
                    fileList.splice(fileList.length - 1, 1);
                    return false;
                }
                if (curType != this.uploadType) {
                    if (this.uploadType == 1) {
                        this.$message.error('请上传图片!');
                        fileList.splice(fileList.length - 1, 1);
                        return false;
                    } else {
                        this.$message.error('最多上传1条视频!');
                        fileList.splice(1, 1);
                        return false;
                    }
                }
            }
            if (this.uploadType == 1) {
                // 图片格式
                if (fileList.length > 9) {
                    this.$message.error('最多上传9张图片!');
                    fileList.splice(0, 9);
                    return false;
                }
                const isJPG = file.raw.type == 'image/png' || file.raw.type == 'image/jpg' || file.raw.type == 'image/jpeg';
                const isLt5M = file.raw.size / 1024 / 1024 < 5;
                if (!isJPG) {
                    this.$message.error('上传图片只能是 jpg、jpeg、png格式!');
                    for (let i = fileList.length - 1; i >= 0; i--) {
                        const element = fileList[i];
                        if (file.name == element.name) {
                            fileList.splice(i, 1);
                        }
                    }
                    return false;
                }
                if (!isLt5M) {
                    this.$message.error('上传图片大小不能超过 5M!');
                    for (let i = fileList.length - 1; i >= 0; i--) {
                        const element = fileList[i];
                        if (file.name == element.name) {
                            fileList.splice(i, 1);
                        }
                    }
                    return false;
                }
            } else if (this.uploadType == 2) {
                // 视频格式
                if (file.raw.size / 1024 / 1024 > 800) {
                    this.$message.error('上传视频大小不能超过 800M!');
                    fileList = [];
                    return false;
                }
            }
            if (this.uploadType == 2) {
                this.fileList = [];
                fileList = [];
            }
            let fd = new FormData();
            fd.append('file', file.raw);
            this.uploadLoading = true;
            sysFileUpload(fd)
                .then((res) => {
                    if (res.data.code === 0) {
                        let fileMsg = res.data.data;
                        if (this.uploadType == 2) {
                            this.form.imgUrl = [fileMsg.url];
                        } else {
                            this.form.imgUrl.push(fileMsg.url);
                        }
                    }
                    this.uploadLoading = false;
                })
                .catch(() => {
                    this.uploadLoading = false;
                });
        },
        goBack() {
            this.showDetail = false;
        }
    }
};
</script>
<style scoped lang="scss">
.madp-search-head {
    text-align: right;
}
.tag {
    margin: 0 10px 10px 0;
}
.video {
    width: 8rem;
    height: 8rem;
}
</style>
